<?php

// if clause required here for 'seamonkey browser'. Gives warning of: "session already open"
if ( ! session_id() ) {
	session_start();
}

// Don't do anything if Not logged in
if (isset($_SESSION['user'])) {
//	$user=$_SESSION['user'];
	
//print_r($_POST);

	$mode="list";
	unset($category);
	unset($sortselect);
	unset($search);	
	if (isset($_POST['mode'])) { 
		$mode=$_POST['mode'];
		unset($_POST['mode']);
		if ($mode != "list") {
			if ($mode == "addurl") {
				$category=$_POST['category'];
				$name=$_POST['name'];
				$url=$_POST['url'];
				$date=$_POST['date'];
			} else if ($mode == "delete2") {
				$delete=$_POST['linkname'];
			} else if (isset($_POST['category'])) {
				$category=$_POST['category'];
				unset($_POST['category']);
			} else if (isset($_POST['sortselect'])) {
				$sortselect=$_POST['sortselect'];
				unset($_POST['sortselect']);
			} else if (isset($_POST['search'])) {
				if ($_POST['search'] == "Enter Search") {
					$mode="list";
				} else {
					$search=$_POST['search'];
				}
				unset($_POST['search']);
			}
		}
	}
	
	//Setup data from data filesc.
	loadfavorites();
	
	display("");
}
exit;

function loadfavorites() {
	global $favArray,$mode,$delete,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$cntA,$catNumArray;

	// Array for count of number of favorites per category
	$catNumArray = array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

	// Load categories info into array
	$catArray = file("categories.txt");
	
	// Load favorites info into array
	$favArray = file("favorites_user.txt");

	$num=0;
	// Load favorites data into individual arrays
	if (count($favArray) != 0){
		foreach($favArray as $line) {
			$tmpArray= explode("|",$line);
			$categoryA[$num]=$tmpArray[0];
			$catNumArray[$tmpArray[0]]++; // increment correct category counter
			$nameA[$num]=$tmpArray[1];
			$dateA[$num]=$tmpArray[2];
			$urlA[$num]=$tmpArray[3];
			$cntA[$num]=$tmpArray[4];
			$num++;
		}
	}
	
} // End loadfavorites	

function fill($str,$len,$fill) {
	if ( ! "$fill" ) { $fill="&nbsp;"; }
	if ( $len > strlen($str) ) { 
		$str=$str .str_repeat($fill,$len - strlen($str)); 
	} else if ( $len < strlen($str) ) { 
		$str=substr($str,0,$len); 
	}
	return $str;
}

function validate($str) {
	if ( ! "$fill" ) { $fill="&nbsp;"; }
	if ( $len > strlen($str) ) { 
		$str=$str .str_repeat($fill,$len - strlen($str)); 
	} else if ( $len < strlen($str) ) { 
		$str=substr($str,0,$len); 
	}
	return $str;
}

function display($message) {
// access global vars
	global $mode,$delete,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$catNumArray;

	if ($mode == "add") { 
		add("");
	} else if ($mode == "addurl") { 
		addurl();
	} else if ($mode == "delete2") { 
		delete2($delete);
	} else if ($mode == "delete") { 
		delete("");
	} else { 
		listfavs($message);
	}

} // end of display function


function giveHeader() {

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
?>

<!DOCTYPE html
	PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
	* File Name:  favorites.php
	* Author: Arthur Brown SID: 6335497
	* Date Written: 22/10/2009 12:00
	* Version: 1.0
	* Last Modified: 
	* Description: PHP Assignment
-->

<head>
<title>Favorites Page</title>

	<style type="text/css">

    </style>
	
<script type="text/javascript">
	function docatselect() { 
	
		if (document.categoryselect.category.selectedIndex != "default") {  
			document.categoryselect.submit();
		}
	}
	function dosortselect() { 
		if (document.sortselect.sortselect.selectedIndex != 0) {  
			document.sortselect.submit();
		}
	}
	function clearname() { 
		if ( document.addfavorite.name.value == "Enter Link Name" ) {
			document.addfavorite.name.value="";
		}
	}
	function clearurl() { 
		if ( document.addfavorite.url.value == "Enter URL" ) {
			document.addfavorite.url.value="";
		}
	}
	function clearsearch() { 
		if ( document.search.search.value == "Enter Search" ) {
			document.search.search.value="";
		}
	}
	function dodelete($val) { 
		if ( window.confirm("Do you wish to delete the Link: " + $val ) == true ) { 
			document.delete.linkname.value=$val;  
			document.delete.submit();
		}
	}
</script>

</head>

<body>

<?php
	// Home button
	//echo "<br /><br />";
	echo "<form name=\"logout\" method=\"post\" action=\"../../index.php\">";
	echo "<input type=\"submit\" value=\"Home\"/>";
	echo "</form>";

} // end of giveHeader function

function delete2($linkname) {

	global $mode,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$favArray,$catNumArray;

	// delete favorite with linkname 
	$fh=fopen("favorites_user.txt","w");  // Open file for write
	foreach($favArray as $line) {
		$tmpArray= explode("|",$line);
		if ( $tmpArray[1] != $linkname){
			fwrite($fh,$line);
		}
	}
	fclose($fh);  //close the file

	// Reload favorites info into array	
	loadfavorites();
	
	delete("<form name=\"return\" method=\"post\" action=\"favorites.php\"><input name=\"mode\" type=\"hidden\" value=\"list\"/><input type=\"submit\" value=\"Return to 'Your Favorites'\"/></form><br /> " .$linkname ." Is deleted.<br /> Click on the Link Name you wish to delete:");		
	exit;
	
} // end of delete2 function

function delete($message) {

	global $mode,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$favArray,$catNumArray;

	if (count($favArray) == 0){ // No favorites
		listfavs("No favorites to delete.");
		exit;
	}
	
	if ($message == "") { givewelcome("<form name=\"return\" method=\"post\" action=\"favorites.php\"><input name=\"mode\" type=\"hidden\" value=\"list\"/><input type=\"submit\" value=\"Return to 'Your Favorites'\"/></form><br /> Click on the Link Name you wish to delete:");
	} else { givewelcome($message); }
		
	// Show headers of Favorite list
	echo "<form action=\"\">";
	echo "<table width=\"55%\" cellpadding=\"0\" align=\"left\" cellspacing=\"5\">";
	echo "<tr>";
	echo "<th align=\"left\" >Category ";
	if (isset($category) && $category != "no") { echo $catArray[$category] ."</th>"; } else { echo "</th>"; }
	echo "<th align=\"left\" >" .fill("Link Name",55,"")  ."</th>";
	echo "<th align=\"left\" >" .fill("Date",12,"")  ."</th>";
	echo "</tr>";
	$num=0;
	$catcnt=0;
	$count=0;
	$total=count($favArray);

// List favorites to delete
	if (count($favArray) != 0){
		foreach($categoryA as $cat) {
			echo "<tr>";
			echo "<td>" .fill($catArray[$cat],12,"") ."</td>";
			echo "<td><a onclick=\"dodelete('" .$nameA[$num] ."')\" >" .$nameA[$num] ."</a></td>";
			echo "<td>" .fill($dateA[$num],12,"") ."</td>";
			echo "</tr>";
			$num++;
		}
	}
	echo "</table> ";
	echo "</form>";
		
	echo "<form name=\"delete\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"linkname\" type=\"hidden\" value=\"\"/>";
	echo "<input name=\"mode\" type=\"hidden\" value=\"delete2\"/>";
	echo "</form>";
	
?>
</body>
</html>
<?php
} // end of delete function


function add($message) {

	global $mode,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$catNumArray;
	giveHeader();
	echo "<h1> Welcome";  
                      // capitalise usename???
//	if ("$user") { echo " " .ucwords($user); } 
//	if ("$user") { echo " " .$user; }

	echo "</h1>";
	echo "<h1> Add a Favorite:</h1>";
	echo "<h3> Fill in the Favorite information</h3>";
	if (!empty($message)) { echo "&nbsp;&nbsp;&nbsp; " .$message; }  
	echo "<br /><br />";
	echo "<form name=\"return\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"list\"/>";
	echo "<input type=\"submit\" value=\"Return to 'Your Favorites'\"/>";
	echo "</form>";
	
	echo "<br />";

	echo "<form name=\"addfavorite\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"addurl\"/>";
	echo "<input type=\"submit\" value=\"Save Favorite'\"/>";

	echo "<select name=\"category\" >";
	echo "<option value=\"default\" >Select a Category</option>";
	$num=0;
	foreach($catArray as $option) {
		echo "<option value=\"" .$num ."\">" .$option ."</option>";
		$num++;
	}
	echo "</select>";

	echo "<input name=\"name\" type=\"text\" size=\"33\" onfocus=\"clearname()\" value=\"Enter Link Name\"/>";
	echo "<input name=\"url\" type=\"text\" size=\"66\" onfocus=\"clearurl()\" value=\"Enter URL\"/>";
	echo "<input name=\"date\" type=\"text\" size=\"12\" value=\"" .date("Y-m-d") ."\"/>";
	echo "</form>";
	?>

</body>
</html>
<?php

	exit;
}

// Add new Favorite
function addurl() {
	global $mode,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$favArray,$catNumArray;
	$name=htmlentities($name);
	$url=htmlentities($url);
	$date=htmlentities($date);
	
	if ($category=="default"){
		add("ERROR: A category must be selected.");
	} else if (strlen( $name ) == 0) {
		add("ERROR: The Link Name is empty.");
	} else if (strlen( $url ) == 0) {
		add("ERROR: The URL is empty.");
	} else if (strlen( $date ) == 0) {
		add("ERROR: The Date is empty.");
		
	} else if ($name == "Enter Link Name") {
		add("ERROR: The Link Name is empty.");
	} else if ($url == "Enter URL") {
		add("ERROR: The URL is empty.");
		
	} else if (ctype_space( $name )) {
		add("ERROR: Letters or digits must be used in the Link Name.");
	} else if (ctype_space( $url )) {
		add("ERROR: Letters or digits must be used in the URL.");
	} else if (ctype_space( $date )) {
		add("ERROR: The Date format is incorrect.");
		
	} else if (strlen($url) < 10) {
		add("ERROR: The URL has incorrect format, it must start with 'http://'.");

	} else if (strpos( $url,"http://" ) !== 0) {
		add("ERROR: The URL has incorrect format, it must start with 'http://'.");
	}
	if (count($favArray) != 0){
		//Check for duplicated name
		foreach($nameA as $nam) {
			if (strpos($nam,$name)===0) {
				add("ERROR: The Link Name is already in use.");
				exit;
			}
		}
		//Check for duplicated URL
		foreach($urlA as $ur) {
			if (strpos($ur,$url)===0) {
				add("ERROR: The URL is already a favorite.");
				exit;
			}
		}
	}
	$datearray = explode("-",$date);
	$num=0;
	foreach($datearray as $dat){
		if (!ctype_digit($dat)) {
			add("ERROR: The Date format is incorrect.");
			exit;
		}
		if ($num > 2) {
			add("ERROR: The Date format is incorrect.");
			exit;
		}
		$num++;
	}
	if ($num != 3){
		add("ERROR: The Date format is incorrect.");
		exit;
	}
	
	// Save new favorite
	$fh=fopen("favorites_user.txt","a");
	$num=count($favArray);
	$num--;
	if (count($favArray) == 0){  // don't include '\n' if first favorite
		fwrite($fh,$category ."|");
	} else {
		fwrite($fh,"\n" .$category ."|");
	}
	fwrite($fh,$name ."|");
	fwrite($fh,$date ."|");
	fwrite($fh,$url ."|");
	fwrite($fh,$num);
	fclose($fh);  //close the file
	
	// Reload favorites info into array	
	loadfavorites();
	
	$category="no";
	$mode="list";
	listfavs("Link '" .$name ."' added to your favorites.");
	exit;		
} // End function addurl

// Standard listing page functions
function givewelcome($message) {
	
	global $mode,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$catNumArray;
	giveHeader();
	echo "<h1> Welcome";  
                      // capitalise usename???
//	if ("$user") { echo " " .ucwords($user); } 
//	if ("$user") { echo " " .$user; }

	echo "</h1>";
	echo "<h1> Your Favorites:&nbsp;&nbsp;";
	if (isset($category) && $category != "no") {
		echo "(Category: " .$catArray[$category] ." selected)";
	} else if (isset($sortselect)) {
		echo "(Sorted by: " .$sortselect .")";
	}
	echo "</h1>";
	echo $message;
	echo "<br /><br />";

	echo "<table width=\"77%\" cellpadding=\"0\" align=\"left\" cellspacing=\"0\">";

	echo "<tr><td>";
	echo "<form name=\"button\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"list\"/>";
	echo "<input type=\"submit\" value=\"Show all\"/>";
	echo "</form>";
	echo "</td>";

	echo "<td>";
	echo "<form name=\"categoryselect\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"categoryselect\"/>";
	echo "<select name=\"category\" onchange=\"docatselect()\" >";
	echo "<option value=\"default\" >Select a Category</option>";
	$num=0;
	foreach($catArray as $option) {
		echo "<option value=\"" .$num ."\">" .$option ." &nbsp;(" .$catNumArray[$num] .")</option>";
		$num++;
	}
	echo "</select>";
	echo "</form>";
	echo "</td>";

	echo "<td>";
	echo "<form name=\"sortselect\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"sortselect\"/>";
	echo "<select name=\"sortselect\" onchange=\"dosortselect()\" >";
	echo "<option value=\"default\" >Sort Selection</option>";
	echo "<option value=\"Category\" >Category</option>";
	echo "<option value=\"Link Name\" >Link Name</option>";
	echo "<option value=\"Date\" >Date</option>";
	echo "</select>";
	echo "</form>";
	echo "</td>";

	echo "<td>";
	echo "<form name=\"search\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"search\" onclick=\"clearsearch()\" type=\"text\" value=\"Enter Search\"/>";
	echo "</td>";
	echo "<td>";
	echo "<input name=\"mode\" type=\"hidden\" value=\"search\"/>";
	echo "<input type=\"submit\" value=\"Search\"/>";
	echo "</form>";
	echo "</td>";

	echo "<td>";
	echo "<form name=\"button\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"add\"/>";
	echo "<input type=\"submit\" value=\"Add a Favorite\"/>";
	echo "</form>";
	echo "</td>";

	echo "<td>";
	echo "<form name=\"button\" method=\"post\" action=\"favorites.php\">";
	echo "<input name=\"mode\" type=\"hidden\" value=\"delete\"/>";
	echo "<input type=\"submit\" value=\"Delete a Favorite\"/>";
	echo "</form>";
	echo "</td></tr>";
	echo "</table>";
	echo "<br />";

}

function listfavs($message) {

	global $mode,$category,$categoryA,$catArray,$sortselect,$search,$name,$nameA,$date,$dateA,$url,$urlA,$favArray,$catNumArray;

	givewelcome($message);
	// Show headers of Favorite list
	echo "<table width=\"55%\" cellpadding=\"0\" align=\"left\" cellspacing=\"5\">";
	echo "<tr>";
	echo "<th align=\"left\" >Category ";
	if (isset($category) && $category != "no") { echo $catArray[$category] ."</th>"; } else { echo "</th>"; }
	echo "<th align=\"left\" >" .fill("Link Name",55,"")  ."</th>";
	echo "<th align=\"left\" >" .fill("Date",12,"")  ."</th>";
	echo "</tr>";

	if (count($favArray) == 0){
		$total=0;
		$catcnt=0;
	} else {
		$num=0;
		$catcnt=0;
		$count=0;
		$total=count($favArray);
		
		if (isset($mode) && $mode == "list") {

		// List favorites
			foreach($categoryA as $cat) {
				echo "<tr>";
				echo "<td>" .fill($catArray[$cat],12,"") ."</td>";
				echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
				echo "<td>" .fill($dateA[$num],12,"") ."</td>";
				echo "</tr>";
				$num++;
			}
		} else if (isset($mode) && $mode == "categoryselect") {

		// List only 1 category
			if (isset($category) && $category != "no"){
				foreach($categoryA as $cat) {
					if ($category == $cat){
						echo "<tr>";
						echo "<td>" .fill($catArray[$category],12,"") ."</td>";
						echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
						echo "<td>" .fill($dateA[$num],12,"") ."</td>";
						echo "</tr>";
						$catcnt++;
					}
					$num++;
				}
			} 
		} else if (isset($sortselect)) {
			
			// Sort favorites list by categories
			if ($sortselect == "Category") {
				$catcnt=0;
				foreach($catArray as $can) { // text of each category
					$num=0;
					foreach($categoryA as $cat) { // category number of each favorites line
						if ($cat == $catcnt){
							echo "<tr>";
							echo "<td>" .fill($catArray[$cat],12,"") ."</td>";
							echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
							echo "<td>" .fill($dateA[$num],12,"") ."</td>";
							echo "</tr>";
						}
						$num++;
					}
					$catcnt++;
				}
				$catcnt=0;
			} else if ($sortselect == "Link Name") {
				$sortArray = $nameA;
				sort($sortArray);
				foreach($sortArray as $nam) { // unique link name string
					$num=0;
					foreach($nameA as $name) { // Each link name string
						if ($nam == $name){
							echo "<tr>";
							echo "<td>" .fill($catArray[$categoryA[$num]],12,"") ."</td>";
							echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
							echo "<td>" .fill($dateA[$num],12,"") ."</td>";
							echo "</tr>";
						}
						$num++;
					}
				}
			} else if ($sortselect == "Date") {
				$sortArray = $dateA;
				sort($sortArray,$sort_flags = SORT_REGULAR);
				$lastdat="2000-00-00";
				foreach($sortArray as $dat) { // sorted date strings
					if ($dat != $lastdat){
						$num=0;
						foreach($dateA as $date) { // Each date string
							if ($total != $count){ // Don't count more than what is there
								if ($dat == $date){
									echo "<tr>";
									echo "<td>" .fill($catArray[$categoryA[$num]],12,"") ."</td>";
									echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
									echo "<td>" .fill($dateA[$num],12,"") ."</td>";
									echo "</tr>";
									$count++;
								}
								$num++;
								$lastdat=$dat;
							}
						}
					}
				}
			}
		} else if (isset($search)) {
			$num=0;
			foreach($nameA as $name) { // Each link name string
				if (stripos($name,$search) || stripos($name,$search) === 0){ // List link names with search string in 
					echo "<tr>";
					echo "<td>" .fill($catArray[$categoryA[$num]],12,"") ."</td>";
					echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
					echo "<td>" .fill($dateA[$num],12,"") ."</td>";
					echo "</tr>";
					$count++;
				}
				$num++;
			}
			if ($count > 0){
				echo "<tr>";
				if ($count == 1){
					echo "<td colspan=\"3\"><b>Only the above Link contains: '" .$search ."'</b></td>";
				} else {
					echo "<td colspan=\"3\"><b>The above " .$count ." Links contain: '" .$search ."'</b></td>";
				}
				echo "</tr>";
			} else {
				echo "<tr>";
				echo "<td colspan=\"3\"><b>No Links found with search string: '" .$search ."'</b></td>";
				echo "</tr>";
			}
			$num=0;
			foreach($nameA as $name) { // Each link name string
				if (!stripos($name,$search) && stripos($name,$search) !== 0){ // List link names without search string in 
					echo "<tr>";
					echo "<td>" .fill($catArray[$categoryA[$num]],12,"") ."</td>";
					echo "<td><a target=\"_blank\" href=\"" .$urlA[$num] ."\">" .$nameA[$num] ."</a></td>";
					echo "<td>" .fill($dateA[$num],12,"") ."</td>";
					echo "</tr>";
				}
				$num++;
			}
		} 
	}

	echo "<tr><td></td></tr>";

	if (isset($category) && $category != "no"){
		echo "<tr>";
		if ($catcnt == 1) {
			echo "<td colspan=\"3\"><b>" .$catcnt ."</b> Link in Category: <b>" .$catArray[$category] ."</b>, out of a Total of: <b>" .$total ."</b>. </td>";
		} else {
			echo "<td colspan=\"3\"><b>" .$catcnt ."</b> Links in Category: <b>" .$catArray[$category] ."</b>, out of a Total of: <b>" .$total ."</b>. </td>";
		}
		echo "</tr>";
	} else {
		echo "<tr>";
		if ($total == 1) {
			echo "<td colspan=\"3\"><b>" .$total ."</b> Link in Total.</td>";
		} else {
			echo "<td colspan=\"3\"><b>" .$total ."</b> Links in Total.</td>";
		}
		echo "</tr>";
	}
	echo "</table> ";

?>
</body>
</html>
<?php
} // end of listfavs function
?>

